﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Gurucore.Framework.Core.Configuration;

namespace Gurucore.DTOGenerator
{
	public partial class Options : Form
	{
		DTOGeneratorConfiguration m_oDTOGenCfg;
		public Options()
		{
			InitializeComponent();
		}

		private void Options_Load(object sender, EventArgs e)
		{
			m_oDTOGenCfg = (DTOGeneratorConfiguration)Gurucore.Framework.Core.Application.GetInstance().GetGlobalSharedObject<DTOGeneratorConfiguration>().Copy();
			txtNamespace.Text = m_oDTOGenCfg.GeneratedNamespace;
			txtSaveTo.Text = m_oDTOGenCfg.SaveTo;

			foreach (KeyValuePair<string, TypeMappingSet> oEntry in m_oDTOGenCfg.TypeMapping)
			{
				TypeMappingSet oTypeMapping = oEntry.Value;
				TreeNode oDBNode = new TreeNode(oTypeMapping.Provider);
				tvwDBType.Nodes.Add(oDBNode);
				foreach (KeyValuePair<string, TypeMapping> oSubEntry in oTypeMapping.Type)
				{
					TypeMapping oType = oSubEntry.Value;
					TreeNode oTypeNode = new TreeNode(oType.Name);
					oTypeNode.Tag = oType;
					oDBNode.Nodes.Add(oTypeNode);
				}
			}
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			ConfigurationIOManager oCfgIO = new ConfigurationIOManager(Gurucore.Framework.Core.Application.GetInstance().MainConfigFile);
			Gurucore.Framework.Core.Application.GetInstance().SetGlobalSharedObject(m_oDTOGenCfg);
			oCfgIO.Save(m_oDTOGenCfg);
			this.Close();
		}

		private void tvwDBType_AfterSelect(object sender, TreeViewEventArgs e)
		{
			if (e.Node.Tag is TypeMapping)
			{
				txtPrefix.Enabled = cboCSharpType.Enabled = true;
				txtPrefix.Text = ((TypeMapping)e.Node.Tag).Prefix;

				foreach (object oItem in cboCSharpType.Items)
				{
					if (oItem.ToString() == ((TypeMapping)e.Node.Tag).CSharpType)
					{
						cboCSharpType.SelectedItem = oItem;
					}
				}
			}
			else
			{
				txtPrefix.Enabled = cboCSharpType.Enabled = false;
			}
		}

		private void txtPrefix_TextChanged(object sender, EventArgs e)
		{
			((TypeMapping)tvwDBType.SelectedNode.Tag).Prefix = txtPrefix.Text;
		}
	}
}
